﻿using System;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using AvalonDock;
using DCT.ViewModel;
using Infralution.Localization.Wpf;
using System.Windows.Media;
using DCT.AddIn.HostView;
using System.Collections.Generic;
using System.Xml.Linq;
using System.AddIn.Hosting;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace DCT.View
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindowView : UserControl
    {
        #region Constructor

        public MainWindowView()
        {
            LoadViewResources();

            InitializeComponent();

            CultureManager.UICulture = Thread.CurrentThread.CurrentCulture;
            CultureManager.UICultureChanged += CultureManager_UICultureChanged;
            UpdateLanguageMenus();

            this.DataContextChanged += MainWindowView_DataContextChanged;
            this.Loaded += MainWindowView_Loaded;

            _workspaceManagerAdapter = new WorkspaceManagerAdapter(dockManager);
            DockManager = dockManager;
        }

        #endregion //Constructor

        #region Fields

        WorkspaceManagerAdapter _workspaceManagerAdapter;
        MainWindowViewModel _mainWindowViewModel;
        private AutomationHost _automationHost;

        #endregion //Fields

        #region Properties

        public static DockingManager DockManager { get; private set; }

        #endregion //Properties

        #region Methods

        void MainWindowView_Loaded(object sender, RoutedEventArgs e)
        {
            var window = Window.GetWindow(this);
            if (window != null)
            {
                window.PreviewKeyDown += this.HandleWindowPreviewKeyDown;
            }

            MainWindowViewModel mainWindowViewModel = this.DataContext as MainWindowViewModel;

            if (mainWindowViewModel != null)
            {
                _automationHost = new AutomationHost(mainWindowViewModel.DeviceMapRepository);
                string path = Environment.CurrentDirectory;
                AddInStore.Update(path);
                string[] s = AddInStore.RebuildAddIns(path);
                IList<AddInToken> _addInTokens = AddInStore.FindAddIns(typeof(DCTExtendedFunctionHostView), path);

                foreach (AddInToken token in _addInTokens)
                {
                    AddInManagerViewModel.Instance.AddInTokenList.Add(token);
                    DCTExtendedFunctionHostView addIn = token.Activate<DCTExtendedFunctionHostView>(AddInSecurityLevel.FullTrust);
                    AddInManagerViewModel.Instance.AddInList.Add(addIn);

                    addIn.Initialize(_automationHost);
                }
            }

            //_mainWindowViewModel.Init();
        }

        void MainWindowView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.DataContext is MainWindowViewModel)
            {
                _mainWindowViewModel = this.DataContext as MainWindowViewModel;
                //不使用绑定是因为将窗口拉出为浮动窗口时绑定会断开
                dragDeviceBox.Content = _mainWindowViewModel.DragDevices;
            }
        }

        void CultureManager_UICultureChanged(object sender, EventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = CultureManager.UICulture;
            Thread.CurrentThread.CurrentUICulture = CultureManager.UICulture;
            UpdateLanguageMenus();
        }

        void SimplifiedChineseMenuItem_Click(object sender, RoutedEventArgs e)
        {
            CultureManager.UICulture = new CultureInfo("zh-CN");
        }

        void TraditionalChineseMenuItem_Click(object sender, RoutedEventArgs e)
        {
            CultureManager.UICulture = new CultureInfo("zh-TW");
        }

        void EnglishMenuItem_Click(object sender, RoutedEventArgs e)
        {
            CultureManager.UICulture = new CultureInfo("en-US");
        }

        void UpdateLanguageMenus()
        {
            string lang = CultureManager.UICulture.Name;
            SimplifiedChineseMenuItem.IsChecked = (lang == "zh-CN");
            TraditionalChineseMenuItem.IsChecked = (lang == "zh-TW");
            EnglishMenuItem.IsChecked = (lang == "en-US");
        }

        void LoadViewResources()
        {
            // add resources to App level
            string path;
            ResourceDictionary viewResources;

            path = "pack://application:,,,/DCT.View;component/DeviceView/DeviceViewResources.xaml";
            viewResources = new ResourceDictionary()
            {
                Source = new Uri(path)
            };
            Application.Current.Resources.MergedDictionaries.Add(viewResources);

            path = "pack://application:,,,/DCT.View;component/DeviceDecorator/DeviceChrome.xaml";
            viewResources = new ResourceDictionary()
            {
                Source = new Uri(path)
            };
            Application.Current.Resources.MergedDictionaries.Add(viewResources);

            path = "pack://application:,,,/DCT.View;component/WorkspaceDataTemplate.xaml";
            viewResources = new ResourceDictionary()
            {
                Source = new Uri(path)
            };
            Application.Current.Resources.MergedDictionaries.Add(viewResources);
        }

        void HandleWindowPreviewKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.O:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        _mainWindowViewModel.Open_Execute();
                        e.Handled = true;
                    }
                    break;
                case Key.S:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        _mainWindowViewModel.SaveAs_Execute();
                        e.Handled = true;
                    }
                    break;
                default:
                    break;
            }
        }

        void AboutMenuItem_Click(object sender, RoutedEventArgs e)
        {
            AboutBox aboutBox = new AboutBox();
            aboutBox.Show();
        }

        private void AddInMenuItem_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement el = sender as FrameworkElement;
            AddInToken addInToken = el.Tag as AddInToken;
            int index = AddInManagerViewModel.Instance.AddInTokenList.IndexOf(addInToken);
            DCTExtendedFunctionHostView addIn = AddInManagerViewModel.Instance.AddInList[index];
            addIn.UpdateData();
            ShowAddInView(addInToken.Name, addIn.VisualPosition, addIn.GetVisual());
        }

        private void ShowAddInView(string title, int viewPosition, FrameworkElement addInView)
        {
            DockableContent dockableWindow = new DockableContent();
            dockableWindow.Content = addInView;
            dockableWindow.Title = title;

            switch (viewPosition)
            {
                case 1:
                    dockableWindow.ShowAsFloatingWindow(MainWindowView.DockManager, true);
                    break;
                case 2:
                    dockableWindow.Show(MainWindowView.DockManager, AnchorStyle.Left);
                    break;
                case 3:
                    dockableWindow.Show(MainWindowView.DockManager, AnchorStyle.Top);
                    break;
                case 4:
                    dockableWindow.Show(MainWindowView.DockManager, AnchorStyle.Right);
                    break;
                case 5:
                    dockableWindow.Show(MainWindowView.DockManager, AnchorStyle.Bottom);
                    break;
                case 6:
                    dockableWindow.ShowAsDocument(MainWindowView.DockManager);
                    break;
                default:
                    break;
            }
        }

        #endregion //Methods
    }
}
